const handleSRT = require("./SRT");
const handleLRC = require("./LRC");

function parse(content, type) {
  let arr = content.split("\n");
  // Clear the beginning of blank line
  for (let i = 0;i < arr.length;i++) {
    if (arr[i].trim() !== "") {
      // If it is not blank line, the loop will be breaked
      break;
    } else if (arr[i].trim() === "") {
      // If it is blank line, the element will be deleted;
      arr.splice(0, 1);
      i--;
    }
  }
  // Clear the end of blank line
  for (let i = arr.length - 1;i > -1;i--) {
    if (arr[i].trim() !== "") {
      // If it is not blank line, the loop will be breaked
      break;
    } else if (arr[i].trim() === "") {
      // If it is blank line, the element will be deleted;
      arr.splice(arr.length - 1, 1)
    }
  }

  let _type = type === undefined ? subtitleType(arr) : type;
  if (_type === "SRT") {
    return handleSRT(arr);
  } else if (_type === "LRC") {
    return handleLRC(arr);
  }
  return undefined;
}

function subtitleType(content) {
  if (content[0].startsWith("[")) {
    return "LRC";
  } else {
    return "SRT";
  }
}

function getType(content) {
  let arr = content.split("\n");
  // Clear the beginning of blank line
  for (let i = 0;i < arr.length;i++) {
    if (arr[i].trim() !== "") {
      // If it is not blank line, the loop will be breaked
      break;
    } else if (arr[i].trim() === "") {
      // If it is blank line, the element will be deleted;
      arr.splice(0, 1);
      i--;
    }
  }
  // Clear the end of blank line
  for (let i = arr.length - 1;i > -1;i--) {
    if (arr[i].trim() !== "") {
      // If it is not blank line, the loop will be breaked
      break;
    } else if (arr[i].trim() === "") {
      // If it is blank line, the element will be deleted;
      arr.splice(arr.length - 1, 1)
    }
  }

  return subtitleType(arr);
}

module.exports.parse = parse;
module.exports.type = getType;